<template>
  <div class="view-fill">
    <div v-if="!modifyInfo.visible" class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        :need-return="false"
        :btn-list="fullInfo.btnList"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <el-button
            v-if="
              $permission('patrolTask:modify') &&
              infoList.data.status === 1 &&
              infoList.data.orderSource === 1 &&
              infoList.data.patrolPlanId === -2 &&
              createdBySelf
            "
            @click="update"
            >修改</el-button
          >
          <el-button
            v-if="
              $permission('patrolTask:start') &&
              infoList.data.status === 1 &&
              infoList.data.orderSource === 1 &&
              canDo
            "
            @click="start"
            >开始</el-button
          >
          <el-button
            v-if="
              $permission('patrolTask:complete') &&
              infoList.data.status === 2 &&
              infoList.data.orderSource === 1 &&
              canDo
            "
            @click="complete"
            >完成任务</el-button
          >
          <el-button
            v-if="
              $permission('patrolTask:cancel') &&
              (infoList.data.status === 1 || infoList.data.status === 2) &&
              infoList.data.orderSource === 1
            "
            @click="cancel"
            >取消任务</el-button
          >
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="$permission('patrolTask:printOrder')"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
          <el-button
            v-if="$permission('patrolTask:excelOrder')"
            @click="exportExcel"
            >导出excel</el-button
          >
        </template>

        <div class="model-panel model-panel-left">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body model-panel-body-flex">
            <basic-information :info="infoList">
              <template v-slot:basic-remindDuration>
                <span v-if="infoList.data.remindDuration">
                  任务开始前{{ infoList.data.remindDuration || 0
                  }}{{ infoList.data.remindTimeTypeValue || '-' }}
                </span>
                <span v-else>-</span>
              </template>
            </basic-information>
          </div>
        </div>
        <div class="model-panel model-panel-left">
          <div class="model-panel-title patrolTask-data-wrap">
            <Tooltip style="paddingright: 15px" :text="'巡检点'" />
            <div class="patrolTask-data-item">
              <span class="patrolTask-data-item-label">正常：</span>
              <span class="patrolTask-data-item-data">{{
                infoList.data.normalQty || 0
              }}</span>
            </div>
            <div class="patrolTask-data-item">
              <span class="patrolTask-data-item-label">异常：</span>
              <span class="patrolTask-data-item-data">{{
                infoList.data.abnormalQty || 0
              }}</span>
            </div>
            <div class="patrolTask-data-item">
              <span class="patrolTask-data-item-label">待检：</span>
              <span class="patrolTask-data-item-data">{{
                infoList.data.unInspectedQty || 0
              }}</span>
            </div>
          </div>
          <div class="model-panel-body">
            <div class="flex_full_item">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :tab-index="true"
                :check-box="false"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :isDynamic="true"
              >
                <template v-slot:col-preAssetName="scope">
                  <span>{{ scope.row.preAssetName }}</span>
                </template>
              </page-table>
            </div>
          </div>
        </div>
        <div class="model-panel model-panel-right">
          <div class="model-panel-body">
            <div class="flex_full_item">
              <el-tabs v-model="clickName" @tab-click="handleTabClick">
                <el-tab-pane
                  class="model-panel-title"
                  label="基本信息"
                  name="first"
                >
                  <basic-information :info="basicInfoList"> </basic-information>
                </el-tab-pane>
                <el-tab-pane
                  class="model-panel-title"
                  label="操作流水"
                  name="second"
                >
                  <Timeline :list="affairTableInfo.data" />
                </el-tab-pane>
              </el-tabs>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <patrolAreaDetails
      v-if="patrolAreaInfo.visible"
      :id="patrolAreaInfo.id"
      :title="patrolAreaInfo.title"
      v-model:show-dialog="patrolAreaInfo.visible"
      :order-status="infoList.data.status"
      :order-source="infoList.data.orderSource"
      @callback="patrolAreaCallback"
    />
    <patrol-order-modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :id="modifyInfo.id"
      @returnBack="returnModify"
    />
  </div>
</template>

<script setup name="patrolTaskDetail">
import PageTable from '@/components/PageTable'
import { orderOpAffairAll } from '@/api/affair'
import BasicInformation from '@/components/BasicInformation/index'
import Timeline from '@/components/Timeline/index.vue'
import patrolAreaDetails from './patrolAreaDetails'
import patrolOrderModify from './modify'
import { getCustomizeSetting } from '@/api/customize'
import { fatchTemplateByCode } from '@/api/base'
import {
  getTaskById,
  getPlanTaskAreaAll,
  taskStart,
  taskCompleted,
  taskCancel,
  excelTaskOrder,
  printTaskOrder,
} from '@/api/patrol.js'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
import { updatePrintCount } from '@/api/mapping'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

const Tooltip = defineAsyncComponent(() => import('@/components/Tooltip/index'))

const props = defineProps(['visible', 'title', 'tableRowId'])

const clickName = ref('first')
const infoList = reactive({
  data: {},
  fieldList: [
    { label: '任务编号', value: 'orderNo' },
    { label: '计划编号', value: 'planOrderNo' },
    { label: '计划名称', value: 'patrolPlanName' },
    { label: '任务状态', value: 'statusValue' },
    { label: '巡检线路', value: 'patrolRouteName' },
    { label: '执行负责人', value: 'execResponseUserName' },
    { label: '执行协同人', value: 'execCoordinationUserName' },
    { label: '计划开始时间', value: 'planStartDate' },
    { label: '计划结束时间', value: 'planFinishDate' },
    { label: '提醒于', value: 'remindDuration', type: 'slot' },
    //{ label: "执行时间", value: "" },
    // { label: "备注", value: "remark", className: "not-br" }
  ],
})
const basicInfoList = reactive({
  data: {},
  fieldList: [
    { label: '任务编号', value: 'orderNo' },
    { label: '计划编号', value: 'planOrderNo' },
    { label: '计划名称', value: 'patrolPlanName' },
    { label: '任务状态', value: 'statusValue' },
    { label: '执行负责人', value: 'execResponseUserName' },
    { label: '执行协同人', value: 'execCoordinationUserName' },
    { label: '巡检线路', value: 'patrolRouteName' },
    { label: '计划开始时间', value: 'planStartDate' },
    { label: '计划结束时间', value: 'planFinishDate' },
    { label: '工作时长(分)', value: 'workTime' },
    { label: '允许超时(分)', value: 'allowTimeout' },
    { label: '创建人', value: 'createUserName' },
    { label: '创建日期', value: 'createTime' },
    //{ label: "执行时间", value: "" },
    { label: '备注', value: 'remark', type: 'popover' },
  ],
})
const fullInfo = reactive({
  btnList: [
    { value: 'button', type: 'slot' },
    { label: '返回', event: returnBack, show: true },
  ],
})
const filterInfo = reactive({
  sortArr: [],
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.tableRowId,
      },
    },
    queryParams: {},
  },
})
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '详情',
        event: showDetails,
        show: true,
      },
    ],
  },
})
// 操作流水
const affairTableInfo = reactive({
  data: [],
  query: {
    orderType: 59,
    orderId: props.tableRowId,
    sort: 'operate_time desc',
  },
})
const modifyInfo = reactive({
  visible: false,
  title: '',
  id: '',
})
const patrolAreaInfo = reactive({
  visible: false,
  id: '',
  title: '',
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    // 更新父组件visible
    emit('update:visible', newValue)
  },
})

const createdBySelf = computed(() => {
  return (
    infoList.data.createUser === proxy.$store.state.user.userInfo.user.id ||
    proxy.$store.state.user.userInfo.user.type !== 'normal'
  )
})
const canDo = computed(() => {
  return (
    infoList.data.execResponseUser ==
      proxy.$store.state.user.userInfo.user.id ||
    infoList.data.execCoordinationUser ==
      proxy.$store.state.user.userInfo.user.id ||
    proxy.$store.state.user.userInfo.user.type !== 'normal'
  )
})
watch(
  () => props.tableRowId,
  (newVal) => {
    affairTableInfo.query.orderId = newVal
    filterInfo.query.queryMap.orderId.value = newVal
    getMain()
    getCustomize()
  },
  {
    immediate: true,
    deep: true,
  }
)

tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
})

function returnModify() {
  if (props.tableRowId) {
    getMain()
    getCustomize()
  }
}
function start() {
  //开始
  taskStart(props.tableRowId).then((res) => {
    if (res && res.success) {
      getMain()
      getList()

      if (clickName.value == 'second') {
        getAffairList()
      }
    }
  })
}
function update() {
  modifyInfo.id = props.tableRowId
  modifyInfo.title = '巡检任务修改'
  modifyInfo.visible = true
}
function complete() {
  //完成
  proxy
    .$confirm('完成任务后巡检任务不能再修改,是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      taskCompleted(props.tableRowId).then((res) => {
        if (res && res.success) {
          getMain()
          getList()
          if (clickName.value == 'second') {
            getAffairList()
          }
        }
      })
    })
}
function cancel() {
  //取消
  proxy
    .$prompt('请输入取消原因', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: isNotEmptyString,
      inputErrorMessage: '请输入取消原因且不超过200字符',
    })
    .then(({ value }) => {
      const params = {
        id: props.tableRowId,
        cancelReason: value,
      }
      taskCancel(params).then((res) => {
        if (res && res.success) {
          getMain()
          getList()
          if (clickName.value == 'second') {
            getAffairList()
          }
        }
      })
    })
}
function isNotEmptyString(value) {
  if (value == null || typeof value === 'undefined' || value.trim() === '') {
    return false
  } else {
    if (value.length > 200) {
      return false
    }
    return true
  }
}
function handleTabClick(tab) {
  const name = tab.paneName
  if (name == 'first') {
    getMain()
  } else if (name == 'second') {
    getAffairList()
  }
}
function returnBack() {
  //返回
  showDialog.value = false
  emit('returnBack')
}
function showDetails(row) {
  patrolAreaInfo.visible = true
  patrolAreaInfo.id = row.id
  patrolAreaInfo.title = row.preAreaName
}
function patrolAreaCallback() {
  getMain()
  getList()
  if (clickName.value == 'second') {
    getAffairList()
  }
}
//打印
const templateArr = ref([])
const popoverVisible = ref(false)
//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'patrolTaskDetail',
    deptId: infoList.data.deptId,
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            applicationId: infoList.data.id,
            orderId: infoList.data.id,
            orderNo: infoList.data.orderNo,
          },
          callback: printCallback,
          data: {},
        })
      }
    }
  })
}
function printCallback() {}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      applicationId: infoList.data.id,
      orderId: infoList.data.id,
      orderNo: infoList.data.orderNo,
    },
    callback: printCallback,
    data: {},
  })
  popoverVisible.value = false
}
function exportExcel() {
  excelTaskOrder(filterInfo.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function getMain() {
  getTaskById(props.tableRowId).then((resp) => {
    if (resp && resp.success) {
      let data = resp.data
      infoList.data = data
      basicInfoList.data = data
    }
  })
}
function getList() {
  getPlanTaskAreaAll(filterInfo.query).then((res) => {
    if (res && res.success) {
      tableInfo.data = res.data
    }
  })
}
function getAffairList() {
  orderOpAffairAll(affairTableInfo.query).then((resp) => {
    console.log(resp)
    if (resp && resp.success) {
      affairTableInfo.data = resp.data
    }
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'patrolTaskOrderAreaDetailList-com.slip.spd.entity.vo.patrol.PatrolTaskAreaDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      getList()
    }
  })
}
</script>

<style scoped lang="scss">
:deep(.el-tabs__header) {
  padding: 0 2px !important;
  box-sizing: border-box;
}
:deep(.el-tabs__nav-wrap::after) {
  height: 1px !important;
}
.model-panel-left {
  width: 73%;
  float: left;
  margin-right: 10px;
}
.model-panel-right {
  width: 25%;
}
.patrolTask-data-wrap {
  width: 320px;
  display: flex;
  align-items: center;
  .patrolTask-data-item {
    display: flex;
    align-items: center;
    justify-content: center;
    padding-right: 15px;
    color: #333333;
    .patrolTask-data-item-data {
      color: #6dc1a9;
      font-size: 18px;
    }
  }
}
</style>
